import * as React from "react";
import { appContext } from "../hooks/provider";
import { useConfigStore } from "../hooks/store";
import "antd/dist/reset.css";
import { ConfigProvider, theme, Spin } from "antd";
import { SessionManager } from "./views/manager";
import SignInModal from "./signin";

const classNames = (...classes: (string | undefined | boolean)[]) => {
  return classes.filter(Boolean).join(" ");
};

type Props = {
  title: string;
  link: string;
  children?: React.ReactNode;
  showHeader?: boolean;
  restricted?: boolean;
  meta?: any;
  activeTab?: string;
  onTabChange?: (tab: string) => void;
};

const MagenticUILayout = ({
  meta,
  title,
  link,
  showHeader = true,
  restricted = false,
  activeTab,
  onTabChange,
}: Props) => {
  const { darkMode, isAuthenticated, isAuthLoading } = React.useContext(appContext);
  const { sidebar } = useConfigStore();
  const { isExpanded } = sidebar;
  const [isMobileMenuOpen, setIsMobileMenuOpen] = React.useState(false);
  const [showAuthModal, setShowAuthModal] = React.useState(false);

  // Close mobile menu on route change
  React.useEffect(() => {
    setIsMobileMenuOpen(false);
  }, [link]);

  React.useEffect(() => {
    document.getElementsByTagName("html")[0].className = `${
      darkMode === "dark" ? "dark bg-primary" : "light bg-primary"
    }`;
  }, [darkMode]);

  // Show auth modal when not authenticated and not loading
  React.useEffect(() => {
    if (!isAuthLoading && !isAuthenticated) {
      setShowAuthModal(true);
    } else {
      setShowAuthModal(false);
    }
  }, [isAuthenticated, isAuthLoading]);

  const handleAuthSuccess = () => {
    setShowAuthModal(false);
  };

  // Show loading spinner while checking authentication
  if (isAuthLoading) {
    return (
      <div className="h-screen flex items-center justify-center">
        <ConfigProvider
          theme={{
            token: {
              borderRadius: 4,
              colorBgBase: darkMode === "dark" ? "#2a2a2a" : "#ffffff",
            },
            algorithm:
              darkMode === "dark"
                ? theme.darkAlgorithm
                : theme.defaultAlgorithm,
          }}
        >
          <div className="text-center">
            <Spin size="large" />
            <div className="mt-4 text-gray-600">Loading...</div>
          </div>
        </ConfigProvider>
      </div>
    );
  }

  const layoutContent = (
    <div className="h-screen flex">
      {/* Content area */}
      <div
        className={classNames(
          "flex-1 flex flex-col min-h-screen",
          "transition-all duration-300 ease-in-out",
          "md:pl-1",
          isExpanded ? "md:pl-1" : "md:pl-1"
        )}
      >
        <ConfigProvider
          theme={{
            token: {
              borderRadius: 4,
              colorBgBase: darkMode === "dark" ? "#2a2a2a" : "#ffffff",
            },
            algorithm:
              darkMode === "dark"
                ? theme.darkAlgorithm
                : theme.defaultAlgorithm,
          }}
        >
          <main className="flex-1 p-1 text-primary" style={{ height: "100%" }}>
            <SessionManager />
          </main>
        </ConfigProvider>
        <div className="text-sm text-primary mt-2 mb-2 text-center">
          Magentic-UI can make mistakes. Please monitor its work and intervene if
          necessary.
        </div>
      </div>

      {/* Authentication Modal */}
      <SignInModal
        isVisible={showAuthModal}
        onClose={() => {}} // Cannot close without authentication
        onAuthSuccess={handleAuthSuccess}
      />
    </div>
  );

  // For restricted pages, check authentication
  if (restricted) {
    return (
      <appContext.Consumer>
        {(context: any) => {
          if (context.isAuthenticated) {
            return layoutContent;
          }
          return null;
        }}
      </appContext.Consumer>
    );
  }

  // For non-restricted pages, still enforce authentication
  if (!isAuthenticated) {
    return (
      <div className="h-screen flex items-center justify-center">
        <ConfigProvider
          theme={{
            token: {
              borderRadius: 4,
              colorBgBase: darkMode === "dark" ? "#2a2a2a" : "#ffffff",
            },
            algorithm:
              darkMode === "dark"
                ? theme.darkAlgorithm
                : theme.defaultAlgorithm,
          }}
        >
          <div className="text-center">
            <div className="text-gray-600">Please sign in to access Magentic-UI</div>
          </div>
          <SignInModal
            isVisible={showAuthModal}
            onClose={() => {}} // Cannot close without authentication
            onAuthSuccess={handleAuthSuccess}
          />
        </ConfigProvider>
      </div>
    );
  }

  return layoutContent;
};

export default MagenticUILayout;
